package com.dhh.sky.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONObject;

import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.dao.DataBaseHelper;
import com.dhh.sky.model.SkyDriveAlbum;
import com.dhh.sky.model.SkyDriveAudio;
import com.dhh.sky.model.SkyDriveFile;
import com.dhh.sky.model.SkyDriveFolder;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.model.SkyDrivePhoto;
import com.dhh.sky.model.SkyDriveVideo;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.util.FileViewer;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;

public class CameroUploadService extends IntentService {
	private LiveConnectClient mClient;
	private SharedPreferences sp;
	private final String uploadFolder = "Camera Uploads";
    private FileManager fManager;
	private DataBaseHelper db;

	public CameroUploadService() {
		super("CameroUploadService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
		fManager = new FileManager(db);		
		sp = getSharedPreferences("camera_upload", 0);
        mClient = ((SDAApplication) getApplication()).getConnectClient();
        SkyDriveObject cameraFolder = fManager.getFileByName(uploadFolder);
        //initial upload folder
        if(cameraFolder == null){
        	JSONObject body = new JSONObject();
    		try {
    			body.put("name", uploadFolder);
    			LiveOperation operation = mClient.post("me/skydrive", body);
    			JSONObject result = operation.getResult();
    			if(result.has(JsonKeys.ERROR)){
    				sendMessage("","",1,1,this.getString(R.string.msg_photo_upload_fail));
        			return;
    			}else{
    				cameraFolder = initObject(result.toString(),String.valueOf(new Date().getTime()));
    				fManager.addFile(cameraFolder);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			sendMessage("","",1,1,this.getString(R.string.msg_photo_upload_fail));
    			return;
    		}
        }else{
        	try {
        		LiveOperation operation = mClient.get(cameraFolder.getId());
    			JSONObject result = operation.getResult();
        		if(result.has(JsonKeys.ERROR)){
        			fManager.delFile(cameraFolder.getId());
        			JSONObject body = new JSONObject();
            		body.put("name", uploadFolder);
        			LiveOperation op = mClient.post("me/skydrive", body);
        			JSONObject rlt = op.getResult();
        			if(rlt.has(JsonKeys.ERROR)){
        				sendMessage("","",1,1,this.getString(R.string.msg_photo_upload_fail));
            			return;
        			}else{
        				cameraFolder = initObject(rlt.toString(),String.valueOf(new Date().getTime()));
        				fManager.addFile(cameraFolder);
        			}
    			}
        		
        		
			} catch (Exception e) {
				e.printStackTrace();
    			sendMessage("","",1,1,this.getString(R.string.msg_photo_upload_fail));
    			return;
			}
        }
        
        
        List<File> files = getUploadFiles();
        int current = 0;
        int max = files.size();
        for(File file : files){
    		sendMessage(file.getName(),file.getAbsolutePath(),max,current,"");
    		current ++;	
    		
        	try {
        		LiveOperation opration = mClient.upload(cameraFolder.getId(), file.getName(), file);
        		JSONObject result = opration.getResult();
        		if(result.has(JsonKeys.ERROR)){
        			sendMessage(file.getName(),"",max,current,this.getString(R.string.msg_photo_upload_fail)+": "+file.getName());
        		}else{
        			sp.edit().putString(file.getAbsolutePath(), file.getAbsolutePath()).commit();
        		}
        	}catch(Exception e){
        		e.printStackTrace();
    			sendMessage(file.getName(),"",max,current,this.getString(R.string.msg_photo_upload_fail)+": "+file.getName());
        	}
        }
        
    	sendMessage("","",max,max,"");
	}
	
	private void sendMessage(String name,String path,int max,int current,String msg){
		Intent fIntent = new Intent("CameraUpload");
    	fIntent.putExtra("max", max);
    	fIntent.putExtra("current", current);
    	fIntent.putExtra("name", name);
    	fIntent.putExtra("path", path);
    	sendBroadcast(fIntent);
	}
	
	private List<File> getUploadFiles(){
		List<File> files = new ArrayList<File>();
		File rootsd = Environment.getExternalStorageDirectory();
		File dcim = new File(rootsd.getAbsolutePath() + "/DCIM");
		List<File> photos = FileViewer.getListFiles(dcim.getAbsolutePath());
		
		for(File photo : photos){
			if(sp.getString(photo.getAbsolutePath(), null)==null){
				files.add(photo);
			}
		}		
		return files;
	}
	
	public SkyDriveObject initObject(String json,String sDate){
		try{
			JSONObject skyDriveObject = new JSONObject(json);
			String type = skyDriveObject.optString("type");
			SkyDriveObject obj = null;
	        if (type.equals(SkyDriveFolder.TYPE)) {
	        	obj = new SkyDriveFolder(skyDriveObject);
	        } else if (type.equals(SkyDriveFile.TYPE)) {
	        	obj = new SkyDriveFile(skyDriveObject);
	        } else if (type.equals(SkyDriveAlbum.TYPE)) {
	        	obj = new SkyDriveAlbum(skyDriveObject);
	        } else if (type.equals(SkyDrivePhoto.TYPE)) {
	        	obj = new SkyDrivePhoto(skyDriveObject);
	        } else if (type.equals(SkyDriveVideo.TYPE)) {
	        	obj = new SkyDriveVideo(skyDriveObject);
	        } else if (type.equals(SkyDriveAudio.TYPE)) {
	        	obj = new SkyDriveAudio(skyDriveObject);
	        } else {
	        	obj = new SkyDriveFile(skyDriveObject);
	        }
	        
	        if(obj!=null){
	        	obj.setMeta(sDate);
	        	return obj;
	        }
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
}